package com.weds.data_sync.advice;

import com.alibaba.fastjson2.JSON;
import com.weds.data_sync.annotation.IgnoreResponseHandler;
import com.weds.data_sync.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description 统一响应体格式
 * @Author lihw
 * @Date 2024/1/4 10:33
 */
@Slf4j
@RestControllerAdvice
public class FormatResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return !returnType.hasMethodAnnotation(IgnoreResponseHandler.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        String path = request.getURI().getPath();
        // 业务接口数据
        if (path.startsWith("/data-sync/api")) {
            JsonData result = null;
            if (body instanceof JsonData) {
                result = (JsonData) body;
            } else {
                result = JsonData.buildSuccess(body);
            }
            // 返回字符串类型需特殊处理
            if (body instanceof String) {
                return JSON.toJSONString(result);
            }

            return result;
        } else {
            // 非业务数据【三方框架:swagger等】
            return body;
        }

    }
}
